// eslint-disable-next-line import/no-unresolved
import React, {Component} from 'react';
import echarts from 'echarts'
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import {dateFormat,convertDateFromString} from '@/utils/time';
import {addResizeHook, removeHook} from "@/utils/resize";


class PredictStatusInfo extends Component {

  state = {
    data: [],
    cache: {
      latestId: null,
      predict_temp: null,
      predict_location: null,
      tempQueue: [],
      locationQueue: []
    },
    chart: null,
    option : {
      title: {
        text: '预测终点'
      },
      legend: {
        data: ['温度', '位置']
      },
      grid: {
        left: '6%',
        right: '6%',
      },
      tooltip: {
        trigger: 'axis',
        formatter(params) {
          const p = params[0];
          const date = new Date(p.name);
          let display = dateFormat(date);
          if (params[0].value[1] && params[1].value[1]) {
            display = `${display}<br>${params[0].seriesName} ${params[0].value[1].toFixed(2)}℃`;
            display = `${display}<br>${params[1].seriesName} ${params[1].value[1].toFixed(2)}m`;
          }

          return display;
        },
        axisPointer: {
          animation: false
        }
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: false
        }
      },
      yAxis: [{
        type: 'value',
        min: 0,
        max: 600,
        name: '温度/℃',
        // interval: 100,
        splitLine: {
          show: false
        }
      }, {
        type: 'value',
        scale: true,
        name: '位置/m',
        min: 65,
        max: 90,
        interval: 10,
      }],
      series: [
        {
          name: '温度',
          type: 'line',
          yAxisIndex: 0,
          showSymbol: false,
          hoverAnimation: false,
          data: null,
          markLine: {
            symbol: "none",
            smooth: false,
            silent: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dotted',
                  color: '#c60c30',
                  width: 2
                },
                label: {
                  show: false,
                  position: 'left'
                }
              }
            },
            data: [
              {
                yAxis: 320,
                yAxisIndex: 0,
                name: "温度上限",
              },

              {
                yAxis: 400,
                yAxisIndex: 0,
                name: "温度下限",
              }
            ]

          }
        },
        {
          name: '位置',
          type: 'line',
          yAxisIndex: 1,
          showSymbol: false,
          hoverAnimation: false,
          data: null,
          markLine: {
            symbol: "none",
            smooth: false,
            silent: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dotted',
                  color: '#5793f3',
                  width: 2
                },
                label: {
                  show: false,
                  position: 'right'
                }
              }
            },
            data: [
              {
                yAxis: 76.44,
                name: "位置上限",
              },

              {
                yAxis: 74.62,
                name: "位置下限",
              }
            ]

          }
        }]
    }
  };


  getLatestId = () => this.state.cache.latestId;



  componentDidMount() {
    const {chartId} = this.props;
    // 基于准备好的dom，初始化echarts实例
    this.state.chart = echarts.init(document.getElementById(chartId));
    // 绘制图表

    this.state.chart.setOption(this.state.option);

    addResizeHook(this,this.state.chart.resize)

  }


  shouldComponentUpdate() {
    return false
  }

  componentWillUnmount() {
    removeHook(this)

  }

  //监听父组件数据更改,return null不做更改
  static getDerivedStateFromProps(nextProps, prevState) {
    const {data} = nextProps;
    // 当传入的type发生变化的时候，更新state
    if (data && data !== prevState.data) {
      const cache = prevState.cache;
      data.forEach(item=>{
        if (cache.latestId !== item.id) {

          cache.latestId = item.id;

          const datetime = convertDateFromString(item.time);

          if (cache.tempQueue.length > 360) {
            cache.tempQueue.shift();
            cache.locationQueue.shift();
          }

          cache.tempQueue.push({
            name: datetime, value: [datetime
              , item.predict_temp]
          });
          cache.locationQueue.push({
            name: datetime, value: [datetime
              , item.predict_location]
          });
        }
      });


      if (prevState.chart !== null) {
        prevState.option.series[0].data = cache.tempQueue;
        prevState.option.series[1].data = cache.locationQueue;

        const arr = cache.locationQueue.map(v => v.value[1]);

        const max = Math.max.apply(null, arr);
        const min = Math.min.apply(null, arr);

        prevState.option.series[1].markArea = { //标记区域
          itemStyle: { //全局的
            normal: { color: '#F0F2F5' }
          },
          data: [
            [{
              yAxis: min,//y轴坐标控制
              itemStyle:{
                color:'#F0F2F5'
              }
            }, {
              yAxis: max
            }]
          ]
        };

        prevState.chart.setOption(prevState.option, true);
      }


      return {
        data,
        cache
      };
    }
    // 否则，对于state不进行任何操作
    return null;
  }


  render() {
    const {
      chartId,
      width = 100,
      height = 300
    } = this.props;

    return (
      <div id={chartId} style={{width: `${width}%`, height}}/>
    )
  }
}

export default PredictStatusInfo
